"""
工作流 API Schema
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List, Dict, Any
from datetime import datetime


# ============ 工作流节点定义 Schema ============

class WorkflowNodeConfig(BaseModel):
    """工作流节点配置"""
    # 根据节点类型,配置项不同,使用 Dict 来灵活处理
    pass


class WorkflowNode(BaseModel):
    """工作流节点定义"""
    id: str = Field(..., description="节点ID")
    type: str = Field(..., description="节点类型")
    name: str = Field(..., description="节点名称")
    config: Dict[str, Any] = Field(default_factory=dict, description="节点配置")
    next: Optional[str] = Field(None, description="下一个节点ID")


class WorkflowDefinition(BaseModel):
    """工作流定义"""
    nodes: List[WorkflowNode] = Field(..., description="节点列表")


# ============ 工作流 CRUD Schema ============

class WorkflowCreate(BaseModel):
    """创建工作流请求"""
    name: str = Field(..., description="工作流名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="工作流描述")
    workflow_definition: WorkflowDefinition = Field(..., description="工作流定义")
    cron_expression: Optional[str] = Field(None, description="Cron 表达式")
    cron_enabled: bool = Field(False, description="是否启用定时调度")
    created_by: Optional[str] = Field(None, description="创建人")

    @field_validator('name')
    @classmethod
    def name_must_not_be_empty(cls, v: str) -> str:
        if not v.strip():
            raise ValueError('工作流名称不能为空')
        return v.strip()


class WorkflowUpdate(BaseModel):
    """更新工作流请求"""
    name: Optional[str] = Field(None, description="新名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="新描述")
    workflow_definition: Optional[WorkflowDefinition] = Field(None, description="新工作流定义")
    cron_expression: Optional[str] = Field(None, description="新 Cron 表达式")
    cron_enabled: Optional[bool] = Field(None, description="是否启用定时调度")


class WorkflowResponse(BaseModel):
    """工作流响应(列表项)"""
    id: int
    name: str
    description: Optional[str] = None
    status: str
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class WorkflowDetailResponse(BaseModel):
    """工作流详情响应"""
    id: int
    name: str
    description: Optional[str] = None
    workflow_definition: Dict[str, Any]
    cron_expression: Optional[str] = None
    cron_enabled: bool
    status: str
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None

    model_config = {"from_attributes": True}


class WorkflowListResponse(BaseModel):
    """工作流列表响应"""
    total: int
    page: int
    page_size: int
    items: List[WorkflowResponse]


# ============ 工作流运行 Schema ============

class WorkflowRunRequest(BaseModel):
    """运行工作流请求"""
    input_params: Optional[Dict[str, Any]] = Field(default_factory=dict, description="输入参数")


class WorkflowRunResponse(BaseModel):
    """运行工作流响应"""
    instance_id: int = Field(..., description="工作流实例ID")
    status: str = Field(..., description="实例状态")


# ============ 工作流实例 Schema ============

class ScheduleConfig(BaseModel):
    """调度配置"""
    # 依赖调度配置
    dependency_instance_ids: Optional[List[int]] = Field(None, description="依赖的实例ID列表")

    # 定时调度配置（一次性）
    scheduled_time: Optional[datetime] = Field(None, description="定时执行时间")

    # CRON调度配置
    cron_expression: Optional[str] = Field(None, description="Cron表达式")


class NodeExecutionInfo(BaseModel):
    """节点执行信息"""
    node_id: str
    node_name: str
    node_type: str
    status: str
    started_at: Optional[datetime] = None
    finished_at: Optional[datetime] = None
    output_data: Optional[Dict[str, Any]] = None
    error_message: Optional[str] = None


class WorkflowInstanceResponse(BaseModel):
    """工作流实例响应(列表项)"""
    id: int
    workflow_id: Optional[int] = None
    instance_name: str
    status: str
    trigger_type: str
    trigger_user: Optional[str] = None
    schedule_type: str = Field(default='manual', description="调度类型")
    schedule_config: Optional[Dict[str, Any]] = Field(None, description="调度配置")
    created_at: datetime
    started_at: Optional[datetime] = None
    finished_at: Optional[datetime] = None
    duration: Optional[int] = None

    model_config = {"from_attributes": True}


class WorkflowInstanceDetailResponse(BaseModel):
    """工作流实例详情响应"""
    id: int
    workflow_id: Optional[int] = None
    template_id: Optional[int] = None
    template_version: Optional[int] = None
    template_name: Optional[str] = None
    instance_name: str
    workflow_definition_snapshot: str
    status: str
    current_node_id: Optional[str] = None
    trigger_type: str
    trigger_user: Optional[str] = None
    schedule_type: str = Field(default='manual', description="调度类型")
    schedule_config: Optional[Dict[str, Any]] = Field(None, description="调度配置")
    input_params: Optional[Dict[str, Any]] = None
    nodes_execution: List[NodeExecutionInfo] = []
    created_at: datetime
    created_by: Optional[str] = None
    started_at: Optional[datetime] = None
    finished_at: Optional[datetime] = None
    duration: Optional[int] = None
    error_message: Optional[str] = None

    model_config = {"from_attributes": True}


class WorkflowInstanceListResponse(BaseModel):
    """工作流实例列表响应"""
    total: int
    page: int
    page_size: int
    items: List[WorkflowInstanceResponse]


class RetryRequest(BaseModel):
    """重试工作流请求"""
    from_node_id: Optional[str] = Field(None, description="从哪个节点开始重试")


# ============ 工作流日志 Schema ============

class WorkflowLogResponse(BaseModel):
    """工作流日志响应"""
    log_time: datetime
    log_level: str
    log_message: str
    node_id: Optional[str] = None

    model_config = {"from_attributes": True}


class WorkflowLogsResponse(BaseModel):
    """工作流日志列表响应"""
    logs: List[WorkflowLogResponse]
